package com.fuyao.cloud.gateway;

import com.fuyao.CommonUtils;
import com.fuyao.license.checker.LicenseVerifyManager;
import com.fuyao.license.checker.LicenseVerifyResult;
import com.fuyao.system.HardwareInfo;
import com.fuyao.system.ServerInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;

@Slf4j
@Component
public class LicenseInstaller {

    private final LicenseVerifyProperties properties;

    public LicenseInstaller(LicenseVerifyProperties properties) {
        this.properties = properties;
        install();
    }

    public void install() {
        if (CommonUtils.isEmpty(properties.getLicensePath())) {
            log.info("++++++++ 证书路径不能为空 ++++++++");
            throw new RuntimeException("证书路径不能为空,请配置 license.verify.license-path");
        }
        log.info("++++++++ 开始安装证书 ++++++++");
        LicenseVerifyManager licenseVerifyManager = new LicenseVerifyManager();
        InputStream resourceAsStream;
        InputStream resourceAsStream1;
        log.debug(ServerInfo.getCurrentDir());
        HardwareInfo hardwareInfo = ServerInfo.getHardwareInfo("");
        log.info(hardwareInfo.toString());
        log.info(hardwareInfo.getCpuSerial());
        log.info(hardwareInfo.getMainBoardSerial());
        log.info(String.join("\n", hardwareInfo.getIpAddress()));
        log.info(String.join("\n", hardwareInfo.getMacAddress()));
        try {
            resourceAsStream = Files.newInputStream(ResourceUtils.getFile(properties.getLicensePath()).toPath());
            resourceAsStream1 = Files.newInputStream(ResourceUtils.getFile(properties.getPublicKeysStorePath()).toPath());
        } catch (IOException e) {
            log.error("++++++++ 读取证书失败 ++++++++", e);
            return;
        }

        LicenseVerifyResult result = licenseVerifyManager.install(properties.getVerifyParam(), resourceAsStream, resourceAsStream1);
        if (result.getResult()) {
            log.info("++++++++ 证书安装成功 ++++++++");
        } else {
            log.info("++++++++ 证书安装失败 ++++++++");
        }
    }
}
